package com.woniuxy.rbac.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.rbac.entity.Member;
import com.woniuxy.rbac.service.MemberService;
import com.woniuxy.rbac.service.PermService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Auther: 老谭（<a href="http://www.woniuxy.com">蜗牛学苑</a>）
 */
public class DbRealm extends AuthorizingRealm {
    @Autowired
    private PermService permService;

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Autowired
    private MemberService memberService;

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", t.getUsername());
//        queryWrapper.eq("password", new String(t.getPassword()));
        Member member = memberService.getOne(queryWrapper);
        if (member == null) {
            throw new UnknownAccountException("账号不存在");
        }
        return new SimpleAuthenticationInfo(member, member.getPassword(), getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
}
